<?php ob_start();session_start();
	include_once "connection.php";
		$sql="Select * from thanhvien where TenThanhVien='".$_SESSION['ThanhVien']."'";
		$KT=mysql_query($sql);
		while($row_tv=mysql_fetch_array($KT,MYSQL_ASSOC))
		{
			$matv=$row_tv['MaThanhVien'];
		}
		//them vao hoa done
		$giatri=$_SESSION['total'];
		if(isset($_POST["DiaChi1"]))
		{
			$diachi=$_POST["DiaChi1"];
		}
		else{
			$diachi="Tự đi lấy hàng";
		}
		$sqlHD="Insert into hoadon(MaThanhVien,DiaChiNhan,HinhThucThanhToan,GiaTriDonHang,SDTNhan,NgayLap,TinhTrang)values('".$matv."','".$diachi."','".$_POST['thanhtoan']."','".$giatri."','".$_POST['DienThoai1']."','".date('h:m:s-d/m/Y')."','Chưa Thanh Toán')";
		$result_HD=mysql_query($sqlHD);
		if($result_HD)
		{
			$sql_select="Select MaHoaDon from hoadon where MaThanhVien='".$matv."' and NgayLap='".date('h:m:s-d/m/Y')."'";
			$result_select=mysql_query($sql_select);
			while($row_select=mysql_fetch_array($result_select)){
				$mahd=$row_select['MaHoaDon'];
			}
			foreach($_SESSION['cart'] as $key=>$value)
			{
				$sql_sp="Select DonGiaDuKien,HinhThuc from sanpham s,khuyenmai k where s.MaKhuyenMai=k.MaKhuyenMai and MaSanPham='".$key."'";
				$result_sp=mysql_query($sql_sp);
				while($row_sp=mysql_fetch_array($result_sp))
				{
					$giaban=($row_sp["DonGiaDuKien"] - (($row_sp["DonGiaDuKien"]*$row_sp["HinhThuc"])/100));
				}
				$sql_CTHD="insert into chitiethoadon(MaHoaDon,MaSanPham,SoLuong,GiaBan)values('".$mahd."','".$key."','".$value."','".$giaban."')";
				$result_CTHD=mysql_query($sql_CTHD);
				if($result_CTHD)
				{
					header("location:../MyModel/CamOn.php?MHD=".$mahd."");
					unset($_SESSION['cart']);
				} 
			} 	
		}
		else{
			echo 'Đặt hàng thất bại';
		}
		
	
?>